#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import json
import time
import httplib
import urllib
import logging
import logging.handlers

from subprocess import Popen, PIPE
from Ump import utils 

LOG = logging.getLogger('Ump.common.http')


def http_exec(proxy_host, host, url, port=27903, timeout=30):
    proxy_host = '127.0.0.1'
    h2 = httplib.HTTPConnection(proxy_host, port, timeout=timeout)
    url = '/%s?%s' %(url, host)
    url = urllib.quote(url)
    h2.putrequest("GET", url)
    h2.putheader('Content-Type', 'application/json')
    h2.putheader('Transfer-Encoding', 'chunked')
    h2.endheaders()
    r2 = h2.getresponse()
    content = r2.read()
    content = json.loads(content)
    stdout = content['stdout']
    stderr = content['stderr']
    if stdout == None:
        stdout = ''
    if stdout.find('No license found.') != -1:
        raise LichLiscenFault('No license found.')
    elif stdout.find('Invalid license.') != -1:
        raise LichLiscenFault('Invalid license.')
    elif stdout.find('License expired.') != -1:
        raise LichLiscenFault('License expired.')
    elif stdout.find('Excess capacity.') != -1:
        raise LichLiscenFault('Excess capacity.')
    if not stderr == '':
        if stderr.find('Errno') != -1:
            index = stderr.find('Errno')
            error = stderr[index+10:].strip('>')
            raise Exception('%s'%error)
        errors = stderr.split('\n')
        errors = [error for error in errors if error.startswith('utils.Exp')]
        error = ''.join(errors)
        if errors == []:
            error = stderr
        raise Exception('%s'%error)
    return stdout

def http_down(proxy_host, port, host, timeout=30):
    proxy_host = '127.0.0.1'
    url = '/io.tar.gz'
    url = url + '?%s'%host
    dir_ = '%s/tmp/ump/host/%s' % (utils.install_path, host)
    utils.make_dir(dir_)
    h2 = httplib.HTTPConnection(proxy_host, port, timeout=timeout)
    url = urllib.quote(url)
    h2.putrequest("GET", url)
    h2.putheader('Content-Type', 'multipart/form-data')
    h2.putheader('Transfer-Encoding', 'chunked')
    h2.endheaders()
    r2 = h2.getresponse()

    content = r2.read()
    fileobj = '%s/%s.tar.gz'%(dir_, time.time())
    with open(fileobj, 'w') as fout:
        fout.write(content)
    return fileobj

def http_download(host=None, port=None, url=None, filepath=None, timeout=300):
    '''

    :param host:
    :return value: download file from agent, saved local as filepath
    '''
    utils.ensure_dir(filepath)
    h2 = httplib.HTTPConnection(host, port, timeout=timeout)
    url = urllib.quote(url)
    h2.putrequest("GET", url)
    h2.endheaders()
    r2 = h2.getresponse()

    content = r2.read()

    with open(filepath, 'w+') as fout:
        fout.write(content)
    return filepath


if __name__ == '__main__':
    host = '192.168.120.73'
    port = '27911'
    url = '/node/report'
    filepath = '/tmp/fusionstor/callhome/192.168.120.73.zip'
    s = http_download(host, port, url, filepath)
